import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { getCookie, setCookie } from 'cookies-next';
import { toast } from 'react-hot-toast';
import { ApiError } from '@/types/api';

// 创建axios实例
export const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 10000,
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = getCookie('auth-token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response;
  },
  async (error: AxiosError<ApiError>) => {
    const originalRequest = error.config as AxiosRequestConfig & { _retry?: boolean };
    
    // 处理401错误（未授权）
    if (error.response?.status === 401 && !originalRequest._retry) {
      // 尝试刷新token的逻辑
      originalRequest._retry = true;
      try {
        // 获取刷新token的接口，如果你有的话
        const refreshToken = getCookie('refresh-token');
        if (refreshToken) {
          const { data } = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/refresh`, {
            refreshToken,
          });
          setCookie('auth-token', data.token);
          api.defaults.headers.common['Authorization'] = `Bearer ${data.token}`;
          return api(originalRequest);
        }
      } catch (err) {
        // 刷新失败，清除认证状态并重定向到登录页
        window.location.href = '/login';
      }
    }

    // 错误提示
    const errorMessage = error.response?.data?.message || '发生错误，请稍后再试';
    toast.error(errorMessage);
    
    return Promise.reject(error);
  }
);

export default api; 